package com.galaxy.commom.base.aop;

import com.galaxy.commom.base.constant.SystemConstants;
import com.galaxy.commom.base.enums.DataSourceEnum;
import com.galaxy.commom.base.holder.DbContextHolder;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 数据源注解切面
 * @author caijinbang
 * @date 2018/9/8 23:39
 */
@Slf4j
@Aspect
@Component
public class DataSourceAspect {

  @Pointcut("execution(* com.galaxy.loan.mapper.*.*(..))")
  public void dataSourcePointCut() {
  }

  @Before("dataSourcePointCut()")
  public void doBefore(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    if (method.getName().startsWith(SystemConstants.MAPPER_METHOD_STARTSWITH_SELECT)) {
      // 切换从数据源
      DbContextHolder.setDbType(DataSourceEnum.SLAVE);
    } else {
      // 切换主数据源
      DbContextHolder.setDbType(DataSourceEnum.MASTER);
    }
  }

  @After("dataSourcePointCut()")
  public void doAfter() {
    // 清空数据源
    DbContextHolder.clearDbType();
  }
}
